package com.juzhi.dvrapp.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.IBinder;

import com.juzhi.dvrapp.R;
import com.juzhi.dvrapp.activity.MainActivity;
import com.juzhi.dvrapp.manager.AppManager;
import com.juzhi.dvrapp.manager.DeviceManager;
import com.juzhi.dvrapp.utils.MLog;

import java.text.SimpleDateFormat;
import java.util.Date;

public class BridgeService extends Service {

    private NotificationManager mCustomMgr;
    private DeviceManager deviceManager;
    private NetWorkChangeReveiver netWorkChangeReveiver;
    private LocalBroadcastReceiver localBroadcastReceiver;

    public BridgeService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
        super.onCreate();

        mCustomMgr = (NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);
        initDeviceManager();

        netWorkChangeReveiver = new NetWorkChangeReveiver();
        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(netWorkChangeReveiver, filter);

        localBroadcastReceiver = new LocalBroadcastReceiver();
        IntentFilter filter1 = new IntentFilter();
        filter1.addAction(Intent.ACTION_LOCALE_CHANGED);
        registerReceiver(localBroadcastReceiver, filter1);
    }

    private void initDeviceManager() {
        deviceManager = DeviceManager.getDeviceManager(this.getApplicationContext());
        deviceManager.initialize();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

//        startForeGround();
        return START_STICKY;
    }

    public void startForeGround()
    {
        startForeground(R.mipmap.logo,getNotification(getResources().getString(R.string.app_name)));
    }
    public void stopForeGround()
    {
        this.stopForeground(true);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
//        stopForeGround();
        unregisterReceiver(netWorkChangeReveiver);
        unregisterReceiver(localBroadcastReceiver);
    }

    private Notification getNotification(String message)
    {
        Date date = new Date();
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String strDate = f.format(date);

        PendingIntent pendingIntent ;
        Intent intent;

        String title = this.getResources().getString(R.string.app_name);
        String titlePrompt = title + " " + message;

        intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.setClass(this, MainActivity.class);

        Notification notify = new Notification(R.mipmap.logo, titlePrompt,System.currentTimeMillis());
        notify.flags = Notification.FLAG_ONGOING_EVENT;
        notify.flags |= Notification.FLAG_AUTO_CANCEL;

        pendingIntent = PendingIntent.getActivity(this, R.mipmap.logo,intent, PendingIntent.FLAG_UPDATE_CURRENT);
/*        RemoteViews views = new RemoteViews(this.getPackageName(),R.layout.notification_layout);

        notify.contentIntent = pendingIntent;
        notify.contentView = views;
        notify.contentView.setTextViewText(R.id.no_title, title);
        notify.contentView.setTextViewText(R.id.no_content, message);
        notify.contentView.setTextViewText(R.id.no_time, strDate);
        notify.contentView.setImageViewResource(R.id.no_img, R.drawable.app);*/
//        return notify;


        Notification.Builder builder = new Notification.Builder(this.getApplicationContext()); //获取一个Notification构造器
        builder.setContentIntent(pendingIntent)
                .setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.mipmap.logo))// 设置下拉列表中的图标(大图标)
                .setContentTitle("我是标题")// 设置下拉列表里的标题
                .setSmallIcon(R.mipmap.logo) // 设置状态栏内的小图标
                .setContentText(message) // 设置上下文内容
                .setWhen(System.currentTimeMillis()); // 设置该通知发生的时间
        //.build()最低要求在
        // API16及以上版本上使用，低版本上可以使用.getNotification()。
        Notification notification = builder.build(); // 获取构建好的Notification
//        notification.defaults = Notification.DEFAULT_SOUND; //设置为默认的声音
        return  notification;
    }

    private boolean isFrist = true;
    public class NetWorkChangeReveiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                if (isFrist) {
                    isFrist = false;
                    return;
                }
                MLog.w("网络切换-------");
                ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo mobileNet = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
                NetworkInfo wifiNet = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
                if (wifiNet.isConnected() || mobileNet.isConnected()) {
                    deviceManager.connectionDevice();
                }
            }
        }
    }

    private class LocalBroadcastReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals(Intent.ACTION_LOCALE_CHANGED)){
                MLog.w("语言切换");
                AppManager.getAppManager().AppExit(context);
            }
        }
    }
}
